package com.guocheng.modules.meet.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guocheng.base.BaseService;
import com.guocheng.modules.emp.model.po.Emp;
import com.guocheng.modules.meet.mapper.MeetDao;
import com.guocheng.modules.meet.model.po.Meet;
import com.guocheng.modules.meet.model.po.MeetEmp;
import com.guocheng.modules.meet.model.po.MeetSignin;
import com.guocheng.quartz.meet.StatusQuartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MeetService extends BaseService<MeetDao, Meet> {

    @Autowired
    private MeetSigninService meetSigninService;

    @Autowired
    private MeetEmpService meetEmpService;

    @Autowired
    private StatusQuartz statusQuartz;

    /**
     * 增加会议
     *
     * @param meet 要添加的数据
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public boolean insert(Meet meet) {
        //签到人员信息组装
        empsList(meet);
        //添加会议
        boolean insert = super.insert(meet);

        //添加会议签到信息
        boolean insert1 = meetSigninService.insert(new MeetSignin(meet));

        //添加会议签到人员信息
        meet.getEmps().forEach(t -> t.setStatus(0));
        boolean insert2 = meetEmpService.inserts(meet.getId(), meet.getEmps());

        //添加会议开始和结束的job任务
        statusQuartz.addJob(meet.getStartTime(), meet.getEndTime(), meet.getId());

        return insert & insert1;
    }


    /**
     * 修改会议
     *
     * @param meet 修改的实体类（必须携带id）
     * @return
     */
    @Override
    public boolean updateById(Meet meet) {
        //签到人员信息组装
        empsList(meet);
        //修改会议信息
        boolean update = super.updateById(meet);
        //修改会议签到信息
        boolean update1 = meetSigninService.updateById(new MeetSignin(meet));

        //查询该会议目前所有已经签到的人员状态
        List<MeetEmp> meetEmps = meetEmpService.
                selectList(new MeetEmp(meet.getId()), new QueryWrapper<MeetEmp>().ne("status", 0));
        //获取所有的人员id和状态
        Map<Integer, Integer> map = meetEmps
                .stream().collect(Collectors.toMap(MeetEmp::getEmpId, MeetEmp::getStatus));

        //删除所有该会议的人员
        int i = meetEmpService.deleteByEntity(new MeetEmp(meet.getId()));

        //添加会议签到人员信息
        meet.getEmps().forEach(t -> t.setStatus(map.get(t.getId()) == null ? 0 : map.get(t.getId())));
        boolean update2 = meetEmpService.inserts(meet.getId(), meet.getEmps());

        //修改会议签到定时器
        //如果开始或结束时间超出当前时间，则不修改
        boolean b = statusQuartz.updateJob(meet.getStartTime(), meet.getEndTime(), meet.getId());
        if(!b) throw new RuntimeException("任务修改失败！");

        return update & update1;
    }

    /**
     * 修改会议状态
     *
     * @param id
     * @param status
     * @return
     */
    public boolean updateStatusById(Integer id, Integer status) {
        //修改会议状态
        boolean update = super.updateById(new Meet().setId(id).setStatus(status));

        //获取会议签到状态
        boolean update1 = meetSigninService.updateById(new MeetSignin(id, status));

        return update & update1;
    }

    /**
     * 根据多id删除
     *
     * @param ids 删除的id列表
     * @return 删除条数
     */
    @Transactional(readOnly = false)
    public int deleteByIds(List<Integer> ids) {
        //删除会议签到信息
        int i = meetSigninService.deleteByIds(ids);
        //删除签到人员
        int i1 = meetEmpService.deleteByMeets(ids);
        //删除会议定时任务
        ids.forEach(t->statusQuartz.deleteJob(t));
        //删除会议信息
        return baseDao.deleteBatchIds(ids);
    }

    /**
     * 查询当天所有未结束的会议Id
     *
     * @return
     */
    public List<Meet> selectDayMeet() {
        return baseDao.selectDayMeet();
    }

    /**
     * 修改昨日数据,会议没有结束的直接结束
     *
     * @return
     */
    public int updateYesterday() {
        return baseDao.updateYesterday();
    }

    /**
     * 组装人员信息
     *
     * @param meet
     */
    private void empsList(Meet meet) {
        List<Emp> emps = meet.getEmps();
        //如果没有选择人员，则直接返回
        if (emps != null && emps.size() > 0) {
            //名称组装
            StringBuilder empNames = new StringBuilder();
            empNames.append(emps.get(0).getName());
            //id组装
            StringBuilder empIds = new StringBuilder();
            empIds.append(emps.get(0).getId());
            //将查询出来的信息组装
            for (int i = 1; i < emps.size(); i++) {
                empNames.append(',').append(emps.get(i).getName());
                empIds.append(',').append(emps.get(i).getId());
            }
            //组装后放入meet中
            meet.setEmpNames(empNames.toString());
            meet.setEmpIds(empIds.toString());
            meet.setCount(emps.size());//参会人数
        } else {
            meet.setEmpNames(null);
            meet.setEmpIds(null);
            meet.setCount(0);//参会人数
        }
    }
}
